import _ from 'lodash'
import { getChatRoomInfo } from '../api/Group'
import { getStorage } from '../js/utils.js'
const state = {
  selectMember: {},
  // 当前面板状态：默认页(default)， 人物详情(member), 聊天页(chat)
  chatPanelType: 'member',
  // 当前选中聊天列表(true)或者用户列表(false)
  chatListVisible: false,
  // 当前正在聊天的房间ID
  roomId: '',
  // 存离线消息
  offLineList: [],
  // 聊天信息列表
  chatList: {
    '100008': []
  },
  /**  聊天信息列表的一些状态
   { content,  //文本的草稿信息，
     insertAtArr, //要@的对象数组,
     someoneAtMe,  // 被At的消息提示
   } */
  chatListBase: {
  },
  // 未读数据集合
  unreadList: {},
  // 好友列表
  friendList: [],
  // 群列表
  groupList: [],
  // 所有群聊的成员名单
  chatRoomInfo: {},

  successDataInfo: {},
  // 当前正在播放的音频ID
  audioPlayId: '',
  // 当前右键选中的ID
  clickRightId: ''
}
const mutations = {
  // 别人撤回
  // RECALLCHATLIST (state, payload) {
  //   const { roomId, messageId } = payload
  //   const chatList = _.cloneDeep(state.chatList)
  //   const index = _.findIndex(chatList[roomId], e => e.messageId && e.messageId === messageId)
  //   if (index !== -1) {
  //     chatList[roomId][index].subType = 'recall'
  //   }
  //   state.chatList = Object.assign({}, chatList)
  // },
  // 自己撤回
  WITHDRAWCHATLIST (state, payload) {
    const { roomId, messageId } = payload
    const chatList = _.cloneDeep(state.chatList)
    const index = _.findIndex(chatList[roomId], e => e.messageId && e.messageId === messageId)
    if (index !== -1) {
      chatList[roomId][index].subType = 'withdraw'
    }
    state.chatList = Object.assign({}, chatList)
  },
  SETCHATLISTBASE (state, payload) {
    const { roomId, ...rest } = payload
    let currentBase = state.chatListBase[roomId]
    if (currentBase) {
      currentBase = { ...currentBase, ...rest }
    } else {
      currentBase = rest
    }
    state.chatListBase = { ...state.chatListBase, [roomId]: currentBase }
  },
  AFTEROFUPLOAD (state, payload) {
    const { chatList } = state
    if (chatList[payload.roomId]) {
      const index = _.findIndex(chatList[payload.roomId], e => e.backId === payload.backId)
      if (index !== -1) {
        chatList[payload.roomId][index] = payload
        state.chatList = Object.assign({}, chatList)
      }
    }
  },
  OFFLINELIST (state, payload) {
    const temp = [...state.offLineList, ...payload]
    state.offLineList = temp
  },
  // RESPONESMS (state, payload) {
  //   const { roomId, subType, backId, messageId, sourceId } = payload
  //   const index = _.findIndex(state.chatList[roomId + ''], e => {
  //     return e.backId === backId
  //   })
  //   if (index !== -1) {
  //     let data = { ...state.chatList[roomId + ''][index] }
  //     data.isTemp = false
  //     sourceId && (data.sourceId = sourceId) // sourceId 查找图片的id
  //     data.messageId = messageId // messageId撤回的时候使用标识
  //     data.megState = subType === 'SUCCESS' ? 0 : 2
  //     state.chatList[roomId + ''][index] = data
  //   }
  //   state.chatList = Object.assign({}, state.chatList)
  // },
  CLICKRIGHTID (state, payload) {
    state.clickRightId = payload
  },
  AUDIOPLAYID (state, payload) {
    state.audioPlayId = payload
  },
  CHATROOMINFO (state, payload) {
    state.chatRoomInfo = payload
  },
  ADDCHATROOMINFO (state, payload) {
    const { roomId, data } = payload
    state.chatRoomInfo[roomId] = data
    state.chatRoomInfo = Object.assign({}, state.chatRoomInfo)
  },
  GROUPLIST (state, payload) {
    state.groupList = payload
  },
  // 添加，更新群列表
  ADDGROUPLIST (state, payload) {
    const { roomId, data } = payload
    const index = state.groupList.findIndex(e => e.roomId + '' === roomId)
    if (index !== -1) {
      state.groupList.splice(index, 1)
    }
    state.groupList.push(data)
    state.groupList = [...state.groupList]
  },
  REMOVEGROUPLIST (state, payload) {
    const index = state.groupList.findIndex(e => e.roomId + '' === payload)
    if (index !== -1) {
      state.groupList.splice(index, 1)
      state.groupList = [...state.groupList]
    }
  },
  FRIENDLIST (state, payload) {
    state.friendList = payload
  },
  UNREADLIST (state, payload) {
    state.unreadList = payload
  },
  UPDATEUNREAD (state, payload) {
    const { roomId, num, subType } = payload
    if (subType === 'recall') {
      if (state.unreadList[roomId] <= 0) {
        state.unreadList[roomId] = 0
      } else {
        state.unreadList[roomId] -= num
      }
    }
    if (subType === 'at') {
      state.unreadList[roomId] += num
    }
  },
  ADDUNREADLIST (state, payload) {
    const { roomId, num } = payload
    if (state.unreadList[roomId]) {
      state.unreadList[roomId] += num
    } else {
      state.unreadList[roomId] = num
    }
    state.unreadList = Object.assign({}, state.unreadList)
  },
  DELETEUNERADLISTNUM (state, payload) {
    state.unreadList[payload] = 0
  },
  CHATPANELTYPE (state, payload) {
    state.chatPanelType = payload
    if (payload !== 'member' && state.roomId !== '') {
      state.unreadList[state.roomId] = 0
    }
  },

  /** 聊天消息的处理分为两个粒度
   * 1、对聊天房间的处理，粒度比较大
  *  主要操作有添加，更新，移除
  *  2、对聊天消息的处理，粒度比较小
  *  主要操作有添加，更新和移除
  */
  /** 添加聊天房间
  *  @param {roomId} 房间号
  */
  ADDCHATLIST (state, payload) {
    state.chatList[payload] = []
    state.chatList = { ...state.chatList }
  },
  UPDATECHATLIST (state, payload) {
    const { roomId, data } = payload
    state.chatList[roomId] = data
    state.chatList = { ...state.chatList }
  },
  /** 移除聊天房间
  *  @param {roomId} 房间号
  */
  REMOVECHATLIST (state, payload) {
    delete state.chatList[payload]
    state.chatList = { ...state.chatList }
  },
  /** 聊天信息新增
   *  @param {meg} 单条消息或者数组消息
  */
  ADDCHATLISTMSG (state, payload) {
    const _chatList = { ...state.chatList }
    if (_.isArray(payload)) {
      for (let i = 0; i < payload.length; i++) {
        if (_chatList[payload[i].roomId]) {
          _chatList[payload[i].roomId].push(payload[i])
        } else {
          _chatList[payload[i].roomId] = [payload[i]]
        }
      }
    } else {
      if (_chatList[payload.roomId]) {
        _chatList[payload.roomId].push(payload)
      } else {
        _chatList[payload.roomId] = [payload]
      }
      const data = _.sortBy(_chatList[payload.roomId], e => e.timestamp)
      _chatList[payload.roomId] = data
    }
    state.chatList = _chatList
  },
  // 添加历史数据
  ADD_HISTORY_MSG (state, payLoad) {
    const { roomId, msgList } = payLoad

    const newMsglist = []

    msgList.forEach((item) => {
      const supportedMsgTypes = [
        'bonus','transfer','text', 'image', 'file', 'video', 'audio'
      ]

      if (!supportedMsgTypes.includes(item.subType)) return

      const { data } = item
      const _temp = { ...data, ...item }
      delete _temp.data
      if (item.msgType === 'fileHelper') {
        _temp.isMe = true
        _temp.roomId = '100008'
      }
      if (_temp.senderId === getStorage('aillo_id')) {
        _temp.isMe = true
      }

      newMsglist.push(_temp)
    })

    const _chatList = { ...state.chatList }
    _chatList[roomId].unshift(...newMsglist)

    state.chatList = _chatList
  },
  // 设置接收的消息为已读状态
  SET_MSG_RECEIVER (state, payload) {
    const { roomId, unreadMsgIds } = payload

    const currentChatList = state.chatList[roomId + '']

    unreadMsgIds.forEach(msgId => {
      const index = currentChatList.findIndex((v) => {
        return v.messageId === msgId
      })
      if (index !== -1) {
        currentChatList[index].unread = false
      }
    })

    state.chatList = { ...state.chatList, [roomId]: currentChatList }
  },
  /** 聊天消息更新：
   *  消息发送成功的回执
   *  消息撤回
   *  被好友拉黑，失败消息回执
   *  群封禁，失败消息回执
   *  @param {meg} 单条消息
  */
  UPDATECHATLISTMSG (state, payload) {
    const { roomId, subType, backId, messageId, sourceId } = payload
    const msg = state.chatList[roomId + ''].find(e => (e.backId === backId || e.messageId === messageId))
    if (msg) {
      msg.isTemp = false
      sourceId && (msg.sourceId = sourceId) // sourceId 查找图片的id
      msg.messageId = messageId // messageId撤回的时候使用标识
      switch (subType) {
        case 'SUCCESS':
          msg.megState = 0
          break
        case 'recall':
          msg.subType = 'recall'
          break
        case 'withdraw':
          msg.subType = 'withdraw'
          break
        default:
          msg.megState = 2
      }
    }
    state.chatList = Object.assign({}, state.chatList)
  },
  /** 删除聊天消息
  *  @param {meg} 单条消息
  */
  REMOVECHATLISTMSG (state, payload) {
    const { roomId, backId, messageId } = payload
    const index = state.chatList[roomId + ''].findIndex(e => (e.backId === backId || e.messageId === messageId))
    if (index !== -1) {
      state.chatList[roomId + ''].splice(index, 1)
    }
    state.chatList = Object.assign({}, state.chatList)
  },
  /** 群成员列表操作分为两个粒度
   * 1、群号的操作，粒度比较大
   * 主要操作有初始化，新增，更新
   * 2、群成员的操作，粒度比较小
   * 主要操作有新增、更新和删除
   */
  /** 群成员初始化
   * @param {*} 初始化后的空成员列表
   */
  INITGROUP (state, payload) {
    state.chatRoomInfo = payload
  },
  ADDGROUP (state, payload) {
    state.roomId = payload
  },
  UPDATEGROUP (state, payload) {
    const { roomId, data } = payload
    state.chatRoomInfo[roomId] = data
    state.chatRoomInfo = { ...state.chatRoomInfo }
  },
  ADDGROUPMEMBER (state, payload) {
    const { roomId, data } = payload
    state.chatRoomInfo[roomId].data.push(data)
    state.chatRoomInfo = { ...state.chatRoomInfo }
  },
  UPDATEGROUPMEMBER (state, payload) {
    const { roomId, data, data: { userId } } = payload
    const index = state.chatRoomInfo[roomId].data.findIndex(i => i.userId + '' === userId + '')
    state.chatRoomInfo[roomId].data[index] = data
    state.chatRoomInfo = { ...state.chatRoomInfo }
  },
  REMOVEGROUPMEMBER (state, payload) {
    state.roomId = payload
  },
  /** 初始化群禁言状态
 *  在群详情和群成员数据加载成功后执行
 *  @param {roomId}
*/
  INITGROUPFORBIDDENSTATE (state, payload) {
    const { roomId } = payload
    const myId = sessionStorage.getItem('aillo_id')
    const myInfo = state.chatRoomInfo[roomId].data.find(e => e.userId + '' === myId)
    const groupInfo = state.groupList.find(e => e.roomId + '' === roomId)

    // if顺序不可替换，个人禁言优先级大于全员禁言
    if (groupInfo.forbidSpeakFlag) {
      if (myInfo.adminType === 0) groupInfo.groupState = 'openUserForbidSpeak'
    }
    if (myInfo && myInfo.forbidSpeakFlag) {
      groupInfo.groupState = 'openUserForbidSpeak'
    }
    this.commit('app/ADDGROUPLIST', { roomId, data: groupInfo })
  },

  ROOMID (state, payload) {
    state.roomId = payload
  },
  CHATLISTVISIBLE (state, payload) {
    state.chatListVisible = payload
  },
  SELECTMEMBER (state, payload) {
    state.selectMember = payload
  },
  SUCCESSDATAINFO (state, payLoad) {
    state.successDataInfo = payLoad
  }
}
const actions = {
  addChatRoomInfo ({ commit }, data) {
    commit('ADDCHATROOMINFO', data)
  },
  addUnreadList ({ commit }, data) {
    commit('ADDUNREADLIST', data)
  },
  deleteUnreadList ({ commit }, data) {
    commit('ADDUNREADLIST', data)
  },
  setClickRightId ({ commit }, data) {
    commit('CLICKRIGHTID', data)
  },
  /**
   * 描述
   * @author lin
   * @date 2020-03-16
   * @param {any} {commit}
   * @param {any} data
   * @returns {any}
   */
  setAudioPlayId ({ commit }, data) {
    commit('AUDIOPLAYID', data)
  },
  setChatRoomInfo ({ commit }, data) {
    commit('CHATROOMINFO', data)
  },
  setGroupList ({ commit }, data) {
    commit('GROUPLIST', data)
  },
  addGroupList ({ commit }, data) {
    commit('ADDGROUPLIST', data)
  },
  removeGroupList ({ commit }, data) {
    commit('REMOVEGROUPLIST', data)
  },
  setUnreadList ({ commit }, data) {
    commit('UNREADLIST', data)
  },
  // setChatList ({ commit }, data) {
  //   commit('CHATLIST', data)
  // },
  addChatList ({ commit, dispatch }, data) {
    commit('ADDCHATLIST', data)
    dispatch('updateGroup', data)
  },
  updateChatList ({ commit }, data) {
    commit('UPDATECHATLIST', data)
  },
  removeChatList ({ commit }, data) {
    commit('REMOVECHATLIST', data)
  },
  addChatListMsg ({ state, commit, dispatch }, data) {
    const _chatList = { ...state.chatList }
    if (_.isArray(data)) {
      // for (let i = 0; i < payload.length; i++) {
      //   if (_chatList[payload[i].roomId]) {
      //     _chatList[payload[i].roomId].push(payload[i])
      //   } else {
      //     _chatList[payload[i].roomId] = [payload[i]]
      //   }
      // }
    } else {
      const { roomId } = data
      if (_chatList[roomId]) {
        _chatList[roomId].push(data)
      } else {
        _chatList[roomId] = [data]
        dispatch('updateGroup', data)
      }
      // const sortData = _.sortBy(_chatList[roomId], e => e.timestamp)
      commit('UPDATECHATLIST', { roomId, data: _chatList[ roomId ] })
    }
  },
  updateChatListMsg ({ commit }, data) {
    commit('UPDATECHATLISTMSG', data)
  },
  removeChatListMsg ({ commit }, data) {
    commit('REMOVECHATLISTMSG', data)
  },
  initGroup ({ commit }, data) {
    commit('INITGROUP', data)
  },
  addGroup ({ commit }, data) {
    commit('ADDGROUP', data)
  },
  /** 第一条群聊消息或者发起群聊，并且改群成员数据为空的情况下加载群成员
   *  判断当前群聊的是否禁言
   * @param {roomId|msg}
   */
  async updateGroup ({ state, commit }, data) {
    let _roomId = data
    if (_.isObject(data)) {
      _roomId = data.roomId
    }
    const info = state.chatRoomInfo[_roomId]
    if (info && info.data.length === 0) {
      const res = await getChatRoomInfo(_roomId)
      commit('UPDATEGROUP', { roomId: _roomId, data: res })
      commit('INITGROUPFORBIDDENSTATE', { roomId: _roomId })
    }
  },
  addGroupMember ({ commit }, data) {
    commit('ADDGROUPMEMBER', data)
  },
  updateGroupMember ({ commit }, data) {
    commit('UPDATEGROUPMEMBER', data)
  },
  removeGroupMember ({ commit }, data) {
    commit('REMOVEGROUPMEMBER', data)
  },
  // 设置当前选中的房间，房间未读消息置零
  setRoomId ({ commit }, data) {
    commit('AUDIOPLAYID', '')
    commit('ROOMID', data)
    commit('DELETEUNERADLISTNUM', data)
  },
  setSelectMember ({ commit }, data) {
    commit('SELECTMEMBER', data)
  },
  setChatPanelType ({ commit }, data) {
    commit('CHATPANELTYPE', data)
  },
  setChatListVisible ({ commit }, data) {
    commit('CHATLISTVISIBLE', data)
  },
  setFriendList ({ commit }, data) {
    commit('FRIENDLIST', data)
  },
  setSuccessDataInfo ({ commit }, data) {
    commit('SUCCESSDATAINFO', data)
  }
}
export default {
  namespaced: true,
  state,
  actions,
  mutations
}
